package springmvc;

import org.apache.commons.io.FileUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.nio.charset.StandardCharsets;

@Controller
public class FileController {
    @GetMapping("/tosuccess")
    public String tofile(){
        return "success";
    }

    @PostMapping("/onfiles2")
    public String onfiles2(MultipartFile img[]) throws Exception {
        for (MultipartFile multipartFile : img) {
            if (!multipartFile.isEmpty())//文件不空
            {
                String imgUrl = FileUtil.saveFile(multipartFile);
            }
        }
        return "success";
    }

    @RequestMapping(value="/file/{filename}")
    public ResponseEntity<byte[]> download(HttpServletRequest request,  @PathVariable String filename)throws Exception {
        //下载文件路径
        String path = "C:\\Users\\ZLT\\Desktop";
        File file = new File(path + File.separator + filename);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = new String(filename.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }
}